package com.zwj.design.behavior.observer.demo1.impl;

import com.zwj.design.behavior.observer.demo1.Observer;
import com.zwj.design.behavior.observer.demo1.Subject;

import java.util.ArrayList;

/**
 * 天气信息数据源
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2024/3/16 22:05
 */
public class WeatherData implements Subject {
    /**
     * 记录观察者
     */
    private ArrayList<Observer> observers;
    /**
     * 温度
     */
    private float temperature;
    /**
     * 湿度
     */
    private float humidity;
    /**
     * 压强
     */
    private float pressure;

    /**
     * 无参构造方法：实例化记录观察者容器
     */
    public WeatherData() {
        observers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        int index = observers.indexOf(observer);
        if (index >= 0) {
            observers.remove(index);
        }
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(temperature, humidity, pressure);
        }
    }

    /**
     * 当气象站得到更新观测值时，我们通知观察者
     */
    public void measurementsChanged() {
        this.notifyObservers();
    }

    /**
     * 模拟数据更新
     *
     * @param temperature 温度
     * @param humidity    湿度
     * @param pressure    压强
     */
    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}
